//#include "stdafx.h"
#include "mysql_query_result.h"

namespace utility
{
namespace database
{
    mysql_fields_info::mysql_fields_info(MYSQL_RES *res)
    {
        uint32 num_fields;
        uint32 i;
        MYSQL_FIELD *field;

        num_fields = mysql_num_fields(res);
        for(i = 0; i < num_fields; i++)
        {
            field = mysql_fetch_field_direct(res, i);
            _fields[field->name] = i;
        }
    }

    mysql_query_result::mysql_query_result(MYSQL_RES *res):
        _fields_info(new mysql_fields_info(res))
    {
        reserve(res ? (uint32)mysql_num_rows(res) : 0);

        while (MYSQL_ROW r = mysql_fetch_row(res)) {
            if (const unsigned long* lengths = mysql_fetch_lengths(res)) {
                uint32 field_count = get_field_count();
                //row::list_type values;
                row::pointer temp_row = row::pointer(new row(_fields_info));
                for (unsigned long i = 0; i < field_count; i++)
                {
                    //values.push_back(row::value_type(r[i], lengths[i]));
                    temp_row->push_back(r[i],lengths[i]);
                }
                //push_back(row(_fields_info, values));
                push_back(temp_row);
            }
        }
        
    }

    mysql_query_result::~mysql_query_result()
    {
        delete _fields_info;
    }

    uint32 mysql_query_result::get_field_count() const
    {
        return _fields_info->get_fields_count();
    }

    int32 mysql_query_result::get_field_index(const char * field_name) const
    {
        return (*_fields_info)[field_name];
    }

    const row & mysql_query_result::operator [] (uint32 index) const
    {
        return *(at(index).get());
    }
}
}
